const {BaseService} = require('../../basic.js')
const _ = require('underscore');
const {
	TalentModel
} = require('dx-func-entity')

module.exports = class Talent extends BaseService {
	constructor(ctx) {
		super(ctx);
		this.entity = TalentModel;		
	}
	//初始化
	async getResume({_id}){
		//console.error('debugdebugdebug',this.$dx.auth)
		const result = await this.with(['company','mainCompany']).where({_id}).find();
		if(result&&!_.isEmpty(result.company_list)){
			const _ids = _.pluck(result.company_list,'_id');
			const companys = await this.$dx.service.company.findByIds(_ids);
			const _uids = [];
			const _tids = [];
			_.each(result.company_list,company=>{
				company.relations&&_uids.push(...company.relations);
				company.mates&&_uids.push(...company.mates);
				_tids.push(...(company.teacher||[]));
			});
			let userlist = [];
			let teacherlist = [];
			if(_uids.length){
				userlist = await this.findByIds(_uids);
			}
			if(_tids.length){
				teacherlist = await this.$dx.service.teacher.findByIds(_tids);
			}
			result.company_list = _.map(result.company_list,company=>{
				if(company._id==result.main_company_id){
					result.main_job = company.job;
				}
				if(company.relations){
					company.relationss = _.map(company.relations,_id=>{
						return _.findWhere(userlist,{_id})
					})
				}
				if(company.mates){
					company.matess = _.map(company.mates,_id=>{
						return _.findWhere(userlist,{_id})
					})
				}
				if(company.teacher){
					company.teacher = _.map(company.teacher,_id=>{
						return _.findWhere(teacherlist,{_id})
					})
				}
				const ncompany = _.findWhere(companys,{_id:company._id});
				return {
					...company,
					...ncompany,
				}
			})
		}
		
		return result;
	}
	async getTalents({_ids}){
		const list = await this.with(['company']).where({_id:['in',_ids]}).select();
		return list;
	}
	async getTalentsByCompany({_cid}){
		const list = await this.with(['company']).where({company_id:['in',Array.isArray(_cid)?_cid:[_cid]]}).order('job','desc').limit(100).select();
		return list;
	}
	async getResumes({_ids}){
		const list = await this.with(['company','mainCompany']).where({_id:['in',_ids]}).select();
		const company_ids = [];
		_.each(list,talent=>{
			if(_.isEmpty(talent.company_list))return false;
			const _ids = _.pluck(talent.company_list,'_id');
			company_ids.push(..._ids);
		});
		const companys = await this.$dx.service.company.findByIds(company_ids);
		_.each(list,talent=>{
			if(_.isEmpty(talent.company_list))return false;
			talent.company_list = _.map(talent.company_list,company=>{
				if(company._id==talent.main_company_id){
					talent.main_job = company.job;
				}
				const ncompany = _.findWhere(companys,{_id:company._id});
				return {
					...company,
					...ncompany,
				}
			})
		});
		return list;
	}
	findByIds(_ids){
		return this.where('_id','IN',_ids).limit(3000).field('name,job').select(true);
	}
	findById(_id){
		return this.with(['user','company']).where({_id}).find();
	}
	findWhere(where){
		return this.where(where).limit(3000).field('name,job,mobile,company_id').select();
	}
	async insertTalent({resume,uid,from,extra}){
		/****插入到简历库 START****/
		const userData = {};
		/****************************/
		//resume._id = "66f4d691c3b5c99cfc4e2b3b";
		if(resume._id){
			userData._id = resume._id;
			userData.update_date = new Date().getTime();
			
		}
		if(resume.avatar){
			userData.avatar = await this.$dx.service.index.uploadImg(resume.avatar);
		}
		if(resume.name){
			const name = resume.name.replace(/\*|先生|女士/g,'');
			if(!resume._id){
				userData.name = resume.name;
			}else if(!resume.name.includes('*')&&!resume.name.includes('先生')&&!resume.name.includes('女士')&&name.length>1){
				userData.name = resume.name;
			}
			// if(!resume._id||!resume.name.includes('*')){
			// 	userData.name = resume.name;
			// }
		}
		// if(resume._id&&resume.name&&!resume.name.includes('*')){
		// 	userData.name = resume.name;
		// }
		if(resume.mobile){
			userData.mobile = resume.mobile;
		}
		if(resume.job){
			userData.job = resume.job;
		}
		if(resume.link){
			userData.link = resume.link;
		}
		if(resume.link2){
			userData.link2 = resume.link2;
		}
		if(resume.extra){
			userData.extra = await this.$dx.service.index.uploadBase64(resume.extra);
		}
		if(resume.status){
			userData.status = resume.status;
		}
		if(resume.sex){
			userData.sex = resume.sex;
		}
		if(resume.born){
			userData.born = resume.born;
		}
		if(!_.isEmpty(resume.tags)){
			userData.tags = resume.tags;
		}
		if(!_.isEmpty(resume.target)){
			if(_.isArray(resume.target)){
				const target = resume.target[0];
				target.city = resume.target.map((item) => {
					return item.city;
				}).join('/');
				target.job = resume.target.map((item) => {
					return item.job;
				}).join('/');
				userData.target = target;
			}else{
				userData.target = resume.target;
			}
			
		}
		
		if(!_.isEmpty(resume.companyList)){
			/* 计算主要工作经历的公司 START*/
			const main_company = this.getMainCompany(resume.companyList);
			userData.company_list = resume.companyList.map((item,index)=>{
				if(resume.company==item.name){  // 当前所在的公司
					userData.company_id = item._id;
				}
				if(main_company.name == item.name){
					userData.main_company_id = item._id;
					userData.main_company_name = item.name;
				}
				delete item.service;
				delete item.scale;
				return item;
			});
		}
		if(!_.isEmpty(resume.projectList)){
			userData.project = resume.projectList;
		}
		if(!_.isEmpty(resume.educateList)){
			userData.educate = resume.educateList;
		}
		if(!_.isEmpty(resume.language)){
			userData.language = resume.language;
		}
		if(!_.isEmpty(resume.credential)){
			userData.credential = resume.credential;
		}
		if(!_.isEmpty(resume.skill)){
			userData.skill = resume.skill;
		}
		if(resume.evaluation){
			userData.evaluation = resume.evaluation;
		}
		if(uid&&!resume._id){
			userData.user_id = uid;
		}
		if(uid&&resume._id){
			userData.editor_id = uid;
		}
		if(from){
			userData.from = from;
		}
		resume.from&&(userData.from = resume.from);
		// response2 = await this.$dx.service.grab.save({
		// 	talent_id:response._id,
		// 	project_id:extra._id,
		// 	user_id:this.uid
		// })
		//当前简历所属项目
		if(extra&&extra._id&&!_.isEmpty(resume.project_ids)&&_.isArray(resume.project_ids)){
			userData.project_ids = [...resume.project_ids,extra._id];
		}else if(extra&&extra._id){
			userData.project_ids = [extra._id];
		}
		let result,_id;
		if(resume._id){
			result = await this.update(userData);
			_id = resume._id;
		}else{
			result = await this.insert(userData);
			_id = result;
		}
		return {
			result,
			_id,
			resume:userData
		}
	}
	user() {
	    //  hasOne('表名称','外键名','主键名')，绑定字段到主数据
		return this.hasOne('uni-id-users', 'user_id', '_id').bindField({
			username: 'nickname',
		});
	}
	company() {
	    //  hasOne('表名称','外键名','主键名')，绑定字段到主数据
		return this.hasOne('human-company', 'company_id', '_id').bindField({
			company_name: 'name',
		});
	}
	mainCompany() {
	    //  hasOne('表名称','外键名','主键名')，绑定字段到主数据
		return this.hasOne('human-company', 'main_company_id', '_id').bindField({
			main_company_name: 'name',
		});
	}
	getMainCompany(companys=[]){
		if(_.isEmpty(companys)) return {};
			/* 计算主要工作经历的公司 START*/
			let max = 0;
			let main_company = companys[0];
			companys.forEach((item,index)=>{
				if(_.isArray(item.time)){//计算主要工作经历的公司
					let end = item.time[1]||new Date().getTime();
					let start = item.time[0];
					let gap = end - start;
					if(gap>max){
						max = gap;
						main_company = item
					}
				}
			});
			return main_company;
	}
	async findSimilar({resume,tid,from}){
		
		const where = {};
		if(!resume.name){
			return [];
		}
		if(tid){
			where._id = tid;
			const talents = await this.with(['user','company']).where(where).select();
			const result = this.getSimilar(talents,resume);
			return result.talents;
		}
		const name = (resume.name||'').replace(/\*|先生|女士/g,'');
		let realname = false;
		if(name){
			//const name = resume.name.replace(/\*|先生|女士/g,'');
			//const name = resume.name.substr(0,1);
			// if(from=='liepin'){
			// 	name = resume.name.substr(0,1)
			// }else if(from=='maimai'){
			// 	name = resume.name
			// }
			where.name = ['like',name];
			if(name.length>1){   //默认为真实名字
				realname = true;
				where.name[0] = 'eq';
			}
		}
		
		if(resume.sex&&!realname){
			where.sex = ['eq',resume.sex];
		}
		if(resume.born&&!realname){
			where.born = ['eq',resume.born];
		}
		if(!resume.company&&!_.isEmpty(resume.companyList)){
			resume.company = resume.companyList[0].name;
		}
		if(resume.company){
			const company_name = this.cleanCompanyName(resume.company);
			where['company_list.name'] = ['like',company_name.substr(0,6)];
		}
		// if(!_.isEmpty(resume.companyList)){
		// 	// const main_company = this.getMainCompany(resume.companyList);
		// 	const company_names = _.pluck(resume.companyList,'name');
		// 	where['company_list.name'] = ['in',company_names];
		// }else{
		// 	return [];
		// }
		/*
		* 如果没有公司，且姓名模糊
		*/
		if(!_.isEmpty(resume.educateList)&&(!realname||!resume.company)){
			//where['educate.name'] = ['like',resume.educateList[0].name];
			const educate_names = _.pluck(resume.educateList,'name');
			where['educate.name'] = ['in',educate_names];
		}
		
		//console.error('查询条件：',where);
		const talents = await this.with(['user','company']).where(where).select();
		if(!_.isEmpty(talents)){
			return talents.map(talent=>{
				talent.flag = {
					name:resume.name?true:false,
					sex:resume.sex?true:false,
					born:resume.born?true:false,
					company:!_.isEmpty(resume.companyList)?true:false,
					educate:!_.isEmpty(resume.educateList)?true:false,
				}
				Object.keys(talent.flag).forEach(key=>{
					if(talent.flag[key]==true){
						talent.mcout++;
					}
				});
				return talent
			});
		}
		return this.findNameSimilar({resume,from});
	}
	async findNameSimilar({resume,from}){
		const where = {};
		if(!resume.name)return [];
		let matchName = resume.name.replace(/\*|先生|女士/g,'');
		//let matchName = resume.name.substr(0,1);
		if(!matchName)return [];
		where.name = ['like',matchName];
		/*********************************/
		if(!_.isEmpty(resume.companyList)&&matchName.length==1){
			const company_names = _.pluck(resume.companyList,'name');
			where['company_list.name'] = ['in',company_names];
		}else{
			return [];
		}
		if(!_.isEmpty(resume.educateList)&&matchName.length==1){
			const educate_names = _.pluck(resume.educateList,'name');
			where['educate.name'] = ['in',educate_names];
		}
		/*******************************/
		const list = await this.with(['user','company']).where(where).limit(1000).select();
		/*******************************/
		let {talents,maxCount} = this.getSimilar(list,resume);
		const result = _.filter(talents,talent=>{
			if(talent.mcout==maxCount) return true;
			return false;
		});
		return result;
	}
	getSimilar(talents,resume){
		 let maxCount = 0; //最大匹配数量
		 talents.forEach(talent=>{
		 	const flag = false;
		 	talent.flag = {
				name:this.checkInclude(talent.name.replace(/\*|先生|女士/g,''),resume.name.replace(/\*|先生|女士/g,''))//true
			};
		 	//talent.flag.name = true;
			/*********************************************************/
		 	talent.flag.company = this.checkInclude(talent.company_name,resume.company); // 公司经历
		 	/********工作经历判断 START********/
		 	if(!talent.flag.company&&!_.isEmpty(talent.company_list)&&resume.company){
		 	    talent.company_list.forEach(company=>{
		 			const flag = this.checkInclude(company.name,resume.company); // 公司经历
		 			flag&&(talent.flag.company=true);
		 		})	
		 	}
			if(!talent.flag.company&&!_.isEmpty(talent.company_list)&&!_.isEmpty(resume.companyList)){
			    resume.companyList.forEach(com1=>{
			    	talent.company_list.forEach(com2=>{
			    		if(this.checkInclude(com1.name,com2.name)){
			    			talent.flag.company = true;
							talent.company_name = com2.name;
			    		}
			    	})
			    })
			}
		 	/********教育经历判断 START********/
			if(!_.isEmpty(talent.educate)&&!_.isEmpty(resume.educateList)){
			    resume.educateList.forEach(edu1=>{
					talent.educate.forEach(edu2=>{
						if(this.checkInclude(edu1.name,edu2.name)){
							talent.flag.educate = true;
						}
					})
				})
			}
			/************教育经历判断 END************************/
		 	talent.flag.sex = this.checkInclude(talent.sex,resume.sex);  // 性别
		 	talent.flag.job = this.checkInclude(talent.job,resume.job); // 岗位
		 	talent.flag.born = this.checkInclude(talent.born,resume.born);//年龄
		 	talent.flag.mobile = this.checkInclude(talent.mobile,resume.mobile);//电话
			
		 	talent.mcout = 0;
		 	Object.keys(talent.flag).forEach(key=>{
		 		if(talent.flag[key]==true){
		 			talent.mcout++;
		 		}
		 	})
		 	if(talent.mcout>maxCount)maxCount = talent.mcout;
		});
		return {
			talents,
			maxCount
		} 
	}
	checkInclude(str1="",str2=""){
		if(str1&&str2&&(String(str1).includes(str2)||String(str2).includes(str1))){
			return true;
		}
		return false;
	}
	checkInList(list,key,str){
		const result = _.find(list,item=>{
			return this.checkInclude(item[key],str);
		});
		return result||false;
	}
	/*
	 给定列表集合，查找人员列表 
	*/
	async loadTalentList(key,list){
		/*   查找 HR */
		const tlist = [];
		_.each(list,item=>{
			if(_.isArray(item[key])){
				tlist.push(...item[key]);
			}
		})
		const _tids = _.filter(tlist,item=>_.isString(item));
		const talents = await this.findByIds(_tids);
		for (let i = 0; i < list.length; i++) {
			list[i][key+'s'] = list[i][key].map(_id=>{
				if(_.isString(_id)){
					const talent = _.findWhere(talents,{_id})
					return talent
				}
				return _id;
			});
		}
		return list;
	}
	/*
	*
	*  公司合并 
	* _id  新公司的 id
	* _ids 要合并公司的 ids 集合
	* *
	* */
	async updateCMerge({_id,_ids}){
		//console.error('_ids:',_ids)
		/*
		* 更新所在公司
		*/
		const result1 = await this.where({'company_id':['in',_ids]}).update({
			company_id:_id
		});
		/*
		* 更新主所在公司
		*/
		const result2 = await this.where({'main_company_id':['in',_ids]}).update({
			main_company_id:_id
		});
		/*  
		* 更新工作经历对应的公司
		*/
	    
		const where = {'company_list._id':['in',_ids]};
		const ulist = [];
		const limitCount = 1000;
		let pcount = limitCount;
		while(pcount==limitCount){
			const skip = ulist.length;
			const list = await this.where(where).field('company_list').skip(skip).limit(limitCount).select();
		    pcount = list.length;
			ulist.push(...list);
			//console.error(' 本次查询：',list.length,list);
		}
		//console.error('全部简历数量:',ulist.length);
		let userList = [];
		for(let i = 0;i<ulist.length;i++){
			const talent = ulist[i];
			const company_list = talent.company_list.map(item=>{
				if(_ids.indexOf(item._id)>-1){
					item._id = _id;
					delete item.name;
				}
				return item;
			})
			userList.push({
				_id:talent._id,
				company_list
			});
		    //await this.where({_id:talent._id}).update({company_list});
			//console.error('更新完成：',talent.name,i);
		}
		await this.batchUpdateList(userList,150);
		/**************************/
		return true;
	}
	
	// batchUploadTalent(list){
	// 	const promiseList = [];
	// 	for(let i=0;i<list.length;i++){
	// 		const res = this.update(list[i]);
	// 		promiseList.push(res);
	// 	}
	// 	return Promise.all(promiseList);
	// }
	/*
	 简历合并
	*/
	async updateTMerge({_id,_ids}){
		const result0 = await this.where({'company_list.relations':['contains',_ids]}).field('name,company_list').limit(200).select();
		_.each(result0,talent=>{
			_.each(talent.company_list,company=>{
				company.relations = _.without(company.relations,..._ids);
				if(_id!=talent._id){
					company.relations.push(_id);
				}
			})
		})
		const result1 = await this.where({'company_list.mates':['contains',_ids]}).field('name,company_list').limit(200).select();
		_.each(result1,talent=>{
			_.each(talent.company_list,company=>{
				company.mates = _.without(company.mates,..._ids);
				if(_id!=talent._id){
					company.mates.push(_id);
				}
			})
		})
		const result = [...result0,...result1];
		const result2 = [];
		for(let i = 0;i<result.length;i++){
			const res = await this.update(result[i]);
			res&&result2.push(res)
		}
		return result2;
	}
	async getTalentsByTeacher({_ids}){
		const list = await this.with(['company']).where({'company_list.teacher':['contains',_ids]}).limit(1000).select();
		return list;
	}
	async getTalentsByName({name,company_id}){
		return this.where({company_id:['in',company_id.split(',')],name,from:['neq','liepin']}).find();
	}
	async getBatchTalentsByName({names,company_id}){
		return this.where({company_id:['in',company_id.split(',')],name:['in',names],from:['nin',['liepin','maimai']]}).field('name').select();
	}
	async searchTalent({name,names,company_id}){
		if(name){
			return this.where({company_id:['in',company_id.split(',')],name:['like%',name],from:['neq','liepin']}).find();
		}else if(names){
			return this.getBatchTalentsByName({names,company_id})
		}
	}
	async getSearchTalents({company_id}){
		const jobs = _.range(1,250);
		return this.where({company_id,searched:['neq',1],job:['in',jobs],from:['eq','patent']}).field('name,job').limit(1000).select();
	}
	async resetSearchStatus({company_id}){
		const res = await this.where({company_id,searched:['eq',1],from:['eq','patent']}).update({
			searched:0
		});
		if(res){
			return this.$dx.success('企业简历更新成功');
		}
		return this.$dx.error('不存在已检索简历')
		
	}
	async addPromot({_id,promot}){
		const talent = await this.where({_id}).field('promot_list').find();
		const promot_list = talent.promot_list||[];
		promot_list.push(promot);
		return await this.update({
			_id,
			promot_list
		});
	}
}
